package com.maozzi.api.auth;

import com.alibaba.fastjson.JSON;
import com.maozzi.api.auth.constant.AuthConstant;
import com.maozzi.api.auth.model.UserInfo;
import com.maozzi.api.auth.properties.AuthProperties;
import com.maozzi.common.constant.ErrorCodeConstant;
import com.maozzi.common.exception.BizException;
import com.maozzi.common.model.ResultVO;
import com.maozzi.common.util.AesUtil;
import com.maozzi.common.util.HttpUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录拦截器
 *
 * @author maozi
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 请求头认证参数
     */
    private final String authCookie;

    /**
     * 主机
     */
    private final String host;

    /**
     * 查询用户信息URL
     */
    private final String userInfoUrl;

    /**
     * 查询acl用户信息URL
     */
    private final String aclUserInfoUrl;

    public LoginInterceptor(AuthProperties authProperties) {
        this.authCookie = authProperties.getAuthCookie();
        this.host = authProperties.getHost();
        this.userInfoUrl = authProperties.getUserInfoUrl();
        this.aclUserInfoUrl = authProperties.getAclUserInfoUrl();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String url = request.getRequestURI();
        if (AuthConstant.ERROR_URL.equalsIgnoreCase(url)
                || userInfoUrl.equalsIgnoreCase(url) || aclUserInfoUrl.equalsIgnoreCase(url)) {
            return true;
        }

        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            // 未登录
            throw new BizException(ErrorCodeConstant.NEED_LOGIN, "您好，请先登录");
        }
        UserInfo userInfo = getUserInfo(token);
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BizException(ErrorCodeConstant.NEED_LOGIN, "您好，请先登录");
        }
        return true;
    }

    /**
     * 获取cookie token
     *
     * @param request 请求
     * @return 返回
     */
    private String getToken(HttpServletRequest request) {
        String token = null;
        for (Cookie cookie : request.getCookies()) {
            String name = cookie.getName();
            if (authCookie.equalsIgnoreCase(name)) {
                token = cookie.getValue();
                break;
            }
        }
        return token;
    }

    /**
     * 查询用户数据
     *
     * @param token 令牌
     * @return 返回
     */
    private UserInfo getUserInfo(String token) {
        Map<String, String> headers = new HashMap<>(1);
        headers.put("X-Requested-With", "XMLHttpRequest");
        Map<String, String> params = new HashMap<>(3);
        String timestamp = String.valueOf(System.currentTimeMillis());
        params.put("timestamp", timestamp);
        params.put("sign", AesUtil.encrypt(token, timestamp));
        params.put("token", token);
        String response = HttpUtil.sendGet(host + userInfoUrl, headers, params);
        ResultVO<UserInfo> resultVO = JSON.parseObject(response, ResultVO.class);
        return ObjectUtils.isEmpty(resultVO) ? null : JSON.parseObject(JSON.toJSONString(resultVO.getData()), UserInfo.class);
    }

}
